import logging
import os
from time import sleep
import yaml
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from pages.basepage import Base
from pages.indexpage import IndexPage


class Login(Base):
    # 提取cookie文件路径
    _cookie_file_path = "../pages/work_weixin.yml"
    # _cookie_file_path ="https://work.weixin.qq.com/wework_admin/loginpage_wx"
    _logined_logo = (By.CSS_SELECTOR, ".ww_commonImg_LogoSmall")

    def get_driver_cookie(self):
        if self.find_wait(self._logined_logo) is None:
            # print("30秒内未完成手动扫码登录，请重新运行测试用例并在30秒内完成登录")
            logging.info("30秒内未完成手动扫码登录，请重新运行测试用例并在30秒内完成登录")
            # logging.info(logging.INFO,"30秒内未完成手动扫码登录，请重新运行测试用例并在30秒内完成登录")
        else:
            # print("登录成功")
            logging.info("登录成功")
        # 获取cookie
        cookies = self.driver.get_cookies()
        # 将cookie数据存入到数据库或者文件中
        with open(self._cookie_file_path, "w") as f:
            yaml.safe_dump(cookies, f)

    def add_driver_cookie(self):
        # self.driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx")
        # 定义cookie信息，数据从文件中获取
        with open(self._cookie_file_path) as f:
            cookies = yaml.safe_load(f)
        # 页面添加cookie
        for cookie in cookies:
            self.driver.add_cookie(cookie)

    def login(self):
        # self.driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx")
        if not os.path.exists(self._cookie_file_path):
            self.get_driver_cookie()
        else:
            self.add_driver_cookie()
            logging.info("登录成功")
            self.driver.refresh()
        sleep(3)
        return IndexPage(self.driver)
